package cn.kooki.app.duobao.core;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import java.util.ArrayList;

import cn.kooki.app.duobao.data.Bean.User.ContactInfo;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.util.NetWorkUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.manager.ContactUtils;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2016/1/8.
 */
public class ContactService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        checkupload();
        return super.onStartCommand(intent, flags, startId);
    }




    private void checkupload() {
        final UserInfo userinfo = SharePreferencesUtils.getUserinfo(getApplication());
        boolean islogin = SharePreferencesUtils.getBoolean(getApplication(), SharePreferencesUtils.ISLOGIN);
            if (!TextUtils.isEmpty(userinfo.getUid()) && islogin && NetWorkUtils.isWifiConnected(getApplication())) {
                ContactUtils.getContacts(getApplication(), new ContactUtils.ContactCallback() {
                    @Override
                    public void onQueryCompelete(ArrayList<ContactInfo> infos) {
                        Log.i("contact", "upload");
                        if (infos.size() > 0) {
                            Gson gson = new Gson();
                            String json = gson.toJson(infos);
                            MainFactory.getApiInstance().uploadContacts(userinfo.getUid(), json, new Callback<BaseResponse>() {
                                @Override
                                public void success(BaseResponse baseResponse, Response response) {

                                }

                                @Override
                                public void failure(RetrofitError error) {

                                }
                            });
                        }
                    }
                });
        }
    }
}
